package org.rcy.framework.job.elastic;



import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.lite.internal.server.ServerService;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CleanUnavailableServersJob extends SimpleElasticJob {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private CoordinatorRegistryCenter regCenter;

    public CleanUnavailableServersJob(String cron, CoordinatorRegistryCenter regCenter) {
        super(cron);
        this.regCenter = regCenter;
    }

    public void execute(ShardingContext shardingContext) {
        this.logger.info("Clean unavailable servers.");
        this.regCenter.getChildrenKeys("/").forEach((job) -> {
            this.logger.info("Find job {}", job);
            ServerService serverService = new ServerService(this.regCenter, job);
            this.regCenter.getChildrenKeys(String.format("/%s/%s", job, "servers")).forEach((server) -> {
                if (!serverService.isAvailableServer(server)) {
                    this.regCenter.remove(String.format("/%s/%s/%s", job, "servers", server));
                    this.logger.info("Removed server {} from job {}", server, job);
                }

            });
        });
    }
}